//
//  downLoad.m
//  demo
//
//  Created by james on 15/7/20.
//
//

#import "downLoad.h"
#import "FileModel.h"
#import "ASIHTTPRequest.h"
typedef NS_ENUM(NSInteger, CallBackType) {
    CallBackTypeFinish = 1,
    CallBackTypeInProgress=1 << 1,
    CallBackTypeWillDownload=1 <<2,
    CallBackTypebeginDownload=1 <<3,
    CallBackTypeAbort=1 <<4,
};

@interface  downLoad(){
    NSMutableArray *directories;
  
}
@property (nonatomic,strong) NSFileManager *fm;
@property (nonatomic,strong)  NSMutableDictionary *callBackIds;

@end
@implementation downLoad

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        NSLog(@"downLoad  init method");
    }
    return self;
}
-(NSMutableDictionary*)callBackIds{
    if (!_callBackIds) {
        _callBackIds=[NSMutableDictionary dictionary];
    }
    return _callBackIds;
}
-(FilesDownManage*)downManager{
    if (!_downManager) {
        _downManager= [FilesDownManage sharedFilesDownManageWithBasepath:@"DownLoad" TargetPathArr:[NSArray arrayWithObject:@"DownLoad/mp3"]];
        _downManager.downloadDelegate = self;
        _downManager.VCdelegate=self;
        NSLog(@"%@ class init method",NSStringFromClass(self.class));
    }
    return _downManager;
}
#pragma mark callBackFunction
-(NSString*)stringfromCallBackType:(CallBackType)callbacktype{
   
    return [NSString stringWithFormat:@"%ld",(long)callbacktype];
}
-(void)addfile:(NSString *)fileName CallBackid:(NSString*)callbackid andType:(CallBackType )callBackType{
    
    if (!(fileName&&callbackid&&callBackType)) {//若为nil，直接返回
        return;
    }
//字典以文件名为key，对应的callbackid 和type的字典为值
//   NSDictionary *dic= @{@"qq.exe":@{@"down":@"callbackid2",
//                                    @"progress":@"callbackid1"
//                                }};
    NSString *type=[self stringfromCallBackType:callBackType];
    if ([[self.callBackIds allKeys] containsObject:fileName]) {
        NSMutableDictionary *fileCallback=_callBackIds[fileName];
            [fileCallback setObject:callbackid forKey:type];
    
    }else{
        NSMutableDictionary *fileCallback=[NSMutableDictionary dictionary];
        [fileCallback setObject:callbackid forKey:type];
        [self.callBackIds setObject:fileCallback forKey:fileName];
    }
}
-(NSString *)callbackIdfromfileName:(NSString*)fileName type:(CallBackType)callBackType{
    
    NSString *type=[self stringfromCallBackType:callBackType];
    
    if ([[self.callBackIds allKeys] containsObject:fileName]) {
         NSMutableDictionary *fileCallback=_callBackIds[fileName];
        if ([[fileCallback allKeys] containsObject:type]) {
            return fileCallback[type];
        }
    }
    return nil;
}

-(void)createDownload:(CDVInvokedUrlCommand*) command{
    
  
    NSDictionary *para=[command.arguments firstObject];
    [self addfile:para[@"fileName"] CallBackid:command.callbackId andType:CallBackTypeWillDownload];
    
    [self.downManager downFileUrl:para[@"url"] filename:para[@"fileName"] filetarget:para[@"path"] fileimage:nil fileId:command.callbackId];
    
}
-(void)enumerate:(CDVInvokedUrlCommand*) command{
   
     NSMutableArray *Arrray=[NSMutableArray array];
    
     NSDictionary *para=[command.arguments firstObject];
      if ([para isKindOfClass:[NSNull class]]) {
             return;
            }
        NSString *Satate=para[@"statue"];
    
        if ([Satate isEqualToString:@"finished"]){
                   directories=[NSMutableArray array];
                NSString* path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                   [directories addObject:path];
                   [self getAllDirectoryInDocument:path];
                  Arrray= [CommonHelper getAllFinishFilesListWithPatharr:directories];
            
            
        }else{
            Arrray=[self addFileModelWithSatate:Satate];
        }
    
     CDVPluginResult* result=[CDVPluginResult  resultWithStatus:CDVCommandStatus_OK messageAsArray:Arrray];
   [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
-(void)getAllDirectoryInDocument:(NSString*)path{
    
    [self.fm subpathsAtPath:path];
    NSArray *array=[self.fm contentsOfDirectoryAtPath:path error:Nil ];
    for (int d=0; d<array.count; d++) {
        NSString *detaiPath=[path stringByAppendingPathComponent:array[d]];
        BOOL b=false;
        if ([self.fm fileExistsAtPath:detaiPath isDirectory:&b]&&b) {
            [directories addObject:detaiPath];
            [self getAllDirectoryInDocument:detaiPath];
        }
        
    }
    
}
-(NSMutableArray*)addFileModelWithSatate:(NSString*)state{
   
    NSMutableArray *Arrray=[NSMutableArray array];
    for (FileModel *fileModel in self.downManager.filelist) {
        if (([state isEqualToString:@"isDownload"]||[state isEqualToString:@"isdownload"])&&fileModel.isDownloading) {
          [Arrray addObject:[self dictionaryWithFileModel:fileModel]];
            
        }else if(([state isEqualToString:@"willDownload"]||[state isEqualToString:@"willdownload"])&&fileModel.willDownloading){
            [Arrray addObject:[self dictionaryWithFileModel:fileModel]];
        
        }else{
           [Arrray addObject:[self dictionaryWithFileModel:fileModel]];
        }
        
        
    }
    return Arrray;

}
-(NSDictionary*)dictionaryWithFileModel:(FileModel*)fileModel{
    NSDictionary *dic=@{@"fileID":fileModel.fileID?fileModel.fileID:@"NILL",
                        @"fileName":fileModel.fileName?fileModel.fileName:@"NILL",
                        @"fileSize":fileModel.fileSize?fileModel.fileSize:@"NILL",
                        @"fileType":fileModel.fileType?fileModel.fileType:@"NILL",
                        @"fileReceivedSize":fileModel.fileReceivedSize?fileModel.fileReceivedSize:@"NILL",
                        @"fileURL":fileModel.fileURL?fileModel.fileURL:@"NILL",
                        @"isDownloading":fileModel.isDownloading?@"YES":@"NO",
                        @"willDownloading":fileModel.willDownloading?@"YES":@"NO",
                        @"targetPath":fileModel.targetPath ? fileModel.targetPath:@"NILL"
                        
                        };
    return dic;

}

-(void)clear:(CDVInvokedUrlCommand*) command{
    for (ASIHTTPRequest *request in _downManager.downinglist) {
        if([request isExecuting])
            [request cancel];
        
    }
   

}
-(void)startAll:(CDVInvokedUrlCommand*) command{
    
    [_downManager  restartAllRquests];
}

#pragma mark sigleTast
-(void)abort:(CDVInvokedUrlCommand*) command{//暂停任务，文件也会删除
    
    NSDictionary *para=[command.arguments firstObject];
    BOOL isFileExist=NO;
    for(FileModel *fileModel in _downManager.filelist) {
        if([fileModel.fileName isEqualToString:para[@"filename"]]){
            
        [_downManager abortTaskOfFile:fileModel withRemoveDownload:NO];//已下载不删除文件
            isFileExist=YES;
        }
    }
    if (!isFileExist) {
        NSLog(@"File is not Exist");
    }
}
-(void)addEventListener:(CDVInvokedUrlCommand*) command{//只支持进度监听
    
    
    
    NSString *fileName=[self fileNameFromCommand:command];
    BOOL isFileExist=NO;
    for(FileModel *fileModel in _downManager.filelist) {
        if([fileModel.fileName isEqualToString:fileName]){
            isFileExist=YES;
            fileModel.trackProgress=YES;
            [self addfile:fileName CallBackid:command.callbackId andType:CallBackTypeInProgress];
        }
    }
    
}
-(void)pause:(CDVInvokedUrlCommand*) command{
    
    NSString *fileName=[self fileNameFromCommand:command];
    BOOL isFileExist=NO;
    for(FileModel *fileModel in _downManager.filelist) {
        if([fileModel.fileName isEqualToString:fileName]){
            isFileExist=YES;
            if([CommonHelper isExistFile:fileModel.targetPath]){//文件已下载
                NSLog(@"file is downloaded");
            }
        }
    }
    
    for (ASIHTTPRequest *request in _downManager.downinglist) {
        FileModel *fileInfo=(FileModel*)[request.userInfo objectForKey:@"File"];
        if ([fileInfo.fileName isEqualToString:fileName]) {
              [_downManager stopRequest:request];
            NSLog(@"File pause success");

        }
    }
    if (!isFileExist) {
         NSLog(@"File is not Exist");
    }
    
}
-(BOOL)resume:(CDVInvokedUrlCommand*) command{
    
    NSString *fileName=[self fileNameFromCommand:command];
    BOOL isFileExist=NO;
    for(FileModel *fileModel in self.downManager.filelist) {
        if([fileModel.fileName isEqualToString:fileName]){
            isFileExist=YES;
            if([CommonHelper isExistFile:fileModel.targetPath]){//文件已下载
                NSLog(@"file is downloaded");
                return YES;
            }
        }
    }
    
    for (ASIHTTPRequest *request in self.downManager.downinglist) {
        FileModel *fileInfo=(FileModel*)[request.userInfo objectForKey:@"File"];
        if ([fileInfo.fileName isEqualToString:fileName]) {
            if (fileInfo.post) {
            }else{
                [self.downManager resumeRequest:request];
            }
            
            NSLog(@"File pause success");
            return YES;
        }
        
    }
    if (!isFileExist) {
        NSLog(@"File is not Exist");
        return NO;
    }
    return NO;
}
-(void)start:(CDVInvokedUrlCommand*) command{
    
    BOOL b=[self resume:command];
    NSString *fileName=[self fileNameFromCommand:command];
    if (b) {
        for(FileModel *fileModel in self.downManager.filelist) {
            if([fileModel.fileName isEqualToString:fileName]){
             [_downManager beginRequest:fileModel isBeginDown:YES ];
            }
        }
    }
}
-(NSString*)fileNameFromCommand:(CDVInvokedUrlCommand*) command{
   NSDictionary *para=[command.arguments firstObject];
    return  para[@"filename"];

}

# pragma mark DownloadDelegate
-(void)startDownload:(ASIHTTPRequest *)request{

}
-(void)updateCellProgress:(ASIHTTPRequest *)request{
    
    FileModel *fileInfo=(FileModel *)[request.userInfo objectForKey:@"File"];
    if (fileInfo.trackProgress) {
         NSDictionary *dic=[self dictionaryWithFileModel:fileInfo];
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dic];
        NSString *callBackId=[self callbackIdfromfileName:fileInfo.fileName type:CallBackTypeInProgress];
        if (callBackId) {
            [pluginResult setKeepCallbackAsBool:true];
             [self.commandDelegate sendPluginResult:pluginResult callbackId:callBackId];
        }
    }
    
}
-(void)finishedDownload:(ASIHTTPRequest *)request{
    
    FileModel *fileInfo=(FileModel *)[request.userInfo objectForKey:@"File"];
     NSDictionary *dic=[self dictionaryWithFileModel:fileInfo];
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dic];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:fileInfo.fileID];
}
-(void)allowNextRequest{//允许不断下载， 直到全部下载完
    if(!_isAllowNextRequest){
        return;
    }
    for (int d=0;d<_downManager.filelist.count;d++) {
        FileModel *aFile=_downManager.filelist[d];
            if (!aFile.isDownloading&&(!aFile.willDownloading)) {
                aFile.willDownloading=YES;
            }
    }

    
}//处理一个窗口内连续下载多个文件且重复下载的情况


@end
